package com.wx.mythread.deadlock;


/*
 * description 必然发生死锁的情况
 * author WangXiong
 * createTime 2021/4/4 14:18
 **/
public class MustDeadLock implements Runnable{

    private static Object o1 = new Object();
    private static Object o2 = new Object();

    private int flag;


    /**
     * description 
     * param []
     * return void
     * author WangXiong
     * createTime 2021/4/4 13:47
     **/
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "flag=" + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName() + "同时获取了两把锁");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName() + "同时获取了两把锁");
                }
            }
        }
    }

    public static void main(String[] args) {
        MustDeadLock r1 = new MustDeadLock();
        MustDeadLock r2 = new MustDeadLock();
        r1.flag = 1;
        r2.flag = 0;
        Thread thread1 = new Thread(r1);
        Thread thread2 = new Thread(r2);
        thread1.start();
        thread2.start();
    }
}

